/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package de.editura.oxygen.severin.imageviewer.features;

import de.editura.oxygen.severin.imageviewer.features.io.resources.KnownDataModels;
import de.editura.oxygen.severin.imageviewer.features.knownDatamodels.ImageRefField;
import de.editura.oxygen.severin.imageviewer.features.knownDatamodels.ImageRefFieldCntrllr;
import de.editura.oxygen.severin.imageviewer.features.knownDatamodels.KnownDatamodel;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.text.BadLocationException;
import ro.sync.ecss.extensions.api.AuthorCaretEvent;
import ro.sync.ecss.extensions.api.AuthorCaretListener;
import ro.sync.ecss.extensions.api.AuthorDocumentController;
import ro.sync.ecss.extensions.api.node.AuthorNode;
import ro.sync.exml.editor.EditorPageConstants;
import ro.sync.exml.workspace.api.editor.WSEditor;
import ro.sync.exml.workspace.api.editor.page.author.WSAuthorEditorPage;
import ro.sync.exml.workspace.api.standalone.StandalonePluginWorkspace;

/**
 *
 * @author kschmidtner
 */
public class AutoShowImageAuthorCaretListener implements AuthorCaretListener {

    StandalonePluginWorkspace pluginWorkspaceAccess = null;
    AuthorDocumentController controller = null;
    ImageViewerPanelController imgVPC = null;
    String currentImgRef = "";
    //Todo: Strings for Messages 
    String notFoundStr = "Not Found: ";
    String notUniqueStr = "Not unique: ";
    String noneStr = "NONE";
    String NO_KDM_MSG = "Das automatische Aufrufen der Bilder ist im Moment nur für EAD und TEI möglich.";
    int aktuellesFragmentRootOffSet = 0;
    List<KnownDatamodel> kdmList = KnownDataModels.getInstance().getKdms();


    public AutoShowImageAuthorCaretListener(StandalonePluginWorkspace pluginWorkspaceAccess, ImageViewerPanelController imgVPC) {
        this.pluginWorkspaceAccess = pluginWorkspaceAccess;
        this.imgVPC = imgVPC;
    }

    public void caretMoved(AuthorCaretEvent ace) {
        WSEditor editorAccess = pluginWorkspaceAccess.getCurrentEditorAccess(StandalonePluginWorkspace.MAIN_EDITING_AREA);

        if (editorAccess != null & EditorPageConstants.PAGE_AUTHOR.equals(editorAccess.getCurrentPageID())) {

            WSAuthorEditorPage authorPageAccess = (WSAuthorEditorPage) editorAccess.getCurrentPage();
            int offset = authorPageAccess.getCaretOffset();
            AuthorDocumentController documentController = authorPageAccess.getDocumentController();
            AuthorNode aNode = null;
            try {
                aNode = documentController.getNodeAtOffset(offset);

                KnownDatamodel kdm = isKnownBlockElement(aNode);
                if (kdm != null) {

                    String xmlFormat = kdm.getXmlFormat();
                    String imageFile = findImageRefByNode(ImageRefFieldCntrllr.getImgFileField(kdm.getImgRefFields()).getName()
                            , documentController);
                    String imagePath = "";
                    ImageRefField imgRefPath = ImageRefFieldCntrllr.getImgDirField(kdm.getImgRefFields());
                    if (imgRefPath != null) {
                        if (imgRefPath.getName() != null) {
                             imagePath = findImageRefByNode(imgRefPath.getName(), documentController) + "/";
                        }
                    }

                    String imageRef = imagePath + imageFile;

                    if (!currentImgRef.equals(imageRef)) {
                        //Todo Debuginfo: pluginWorkspaceAccess.showInformationMessage("Das ist caretMoved - TEST!!");
                        imgVPC.refreshImageViewer(imageRef);
                        currentImgRef = imageRef;
                        //Todo Debuginfo: pluginWorkspaceAccess.showInformationMessage("Das ist caretMoved: " + aNode.getName() + " " + imageRef);
                    }
                } else {
                    pluginWorkspaceAccess.showInformationMessage(NO_KDM_MSG);
                }

            } catch (BadLocationException ex) {
                Logger.getLogger(AutoShowImageAuthorCaretListener.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
    }



    private KnownDatamodel isKnownBlockElement(AuthorNode aNode) {
        KnownDatamodel retKdm = null;
        for (KnownDatamodel knownDatamodel : kdmList) {
            if (aNode.getName().equals(knownDatamodel.getCssRootElement())) {
                aktuellesFragmentRootOffSet = aNode.getStartOffset();
                return knownDatamodel;
            } else {
                if (aNode.getParent() != null) {
                    retKdm = isKnownBlockElement(aNode.getParent());
                }
            }
        }
        return retKdm;
    }

    private String findImageRefByNode(String imgRefNodeName, AuthorDocumentController documentController) {
        AuthorNode cardNode;
        AuthorNode fileNode;
        String imageRef = "";
        //Todo Debuginfo: PrintWriter pw = null;

        try {
            ////Todo Debuginfo: pw = new PrintWriter("nodes.txt");
            cardNode = documentController.getNodeAtOffset(aktuellesFragmentRootOffSet);
            fileNode = cardNode;
            int counter = aktuellesFragmentRootOffSet;
            ////Todo Debuginfo: pluginWorkspaceAccess.showInformationMessage("caretMoved: " + cardNode.getName());
            while (!fileNode.getName().equals(imgRefNodeName)) {
                fileNode = documentController.getNodeAtOffset(counter++);
                ////Todo Debuginfo: pw.println(fileNode.getName() + " - " + counter);
            }
            imageRef = fileNode.getTextContent();
            ////Todo Debuginfo: pw.close();
        } catch (BadLocationException ex) {
            Logger.getLogger(AutoShowImageAuthorCaretListener.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(AutoShowImageAuthorCaretListener.class.getName()).log(Level.SEVERE, null, ex);
        }
        return imageRef;
    }

}
